# -*- encoding: utf-8 -*-
"""
@File    :   IP.py
@Time    :   2023-04-06 17:23
@Author  :   坐公交也用券
@Version :   1.0
@Contact :   liumou.site@qq.com
@Homepage : https://liumou.site
@Desc    :   当前文件作用
"""
from loguru import logger
import re
from subprocess import getstatusoutput
import psutil


class EthInfo:
	def __init__(self, debug=False):
		"""
		获取Windows网卡信息
		:param debug: 是否打印调试信息
		"""
		self.debug = debug
		self.eth = ""
		self.ethDicList = []
		self.DefaultDic = {}
		self.gateway = ""
		self.GetEthAll()

	def get_gateway_address(self, ip):
		"""
		通过IP获取对应的网关地址
		:param ip: 需要获取网关的IP地址
		:return:
		"""
		info = getstatusoutput("wmic nicconfig GET INDEX,DefaultIPGateway,IPAddress")
		if info[0] == 0:
			sp = str(info[1]).split("\n")
			for i in sp:
				# Regular expression pattern to match IP address
				pattern = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
				ip_addresses = re.findall(pattern, str(i))
				if len(ip_addresses) >= 1:
					if ip_addresses[1] == ip:
						self.gateway = ip_addresses[0]
						logger.info(f"[ {self.eth} ] 网关获取成功")
						return True
		if self.debug:
			logger.warning(f"[ {self.eth} ]网关获取失败")
		return False

	def GetEthAll(self):
		"""
		获取所有网卡信息
		:return:
		"""
		# 获取所有网卡信息
		net_if_addrs = psutil.net_if_addrs()
		# 遍历网卡信息
		for interface_name, interface_addresses in net_if_addrs.items():
			tmpDic = {}
			for address in interface_addresses:
				if address.family == 2:
					self.eth = interface_name
					tmpDic["name"] = interface_name
					tmpDic["address"] = address.address
					tmpDic["netmask"] = address.netmask
					if self.get_gateway_address(address.address):
						tmpDic["gateway"] = self.gateway
					self.ethDicList.append(tmpDic)
		if self.debug:
			for i in self.ethDicList:
				print(i)

	def GetEthInfoInIp(self, ip):
		"""
		根据IP地址获取网卡信息
		:param ip: IP地址
		:return:
		"""
		for i in self.ethDicList:
			if i["address"] == ip:
				return i
		logger.warning("无法通过当前IP获取网卡信息")
		return False

	def GetEthInfoInName(self, name):
		"""
		根据网卡名称获取网卡信息
		:param name: 网卡名称
		:return:
		"""
		for i in self.ethDicList:
			if i["name"] == name:
				return i
		logger.warning("无法通过当前IP获取网卡信息")
		return False


if __name__ == "__main__":
	eth = EthInfo(debug=False)
	info = eth.GetEthInfoInIp("172.16.1.212")
	print(info)
# eth.GetEthAll()
